<template>
  <div v-if="drawer" class="body_all">
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :append-to-body="true"
      direction="rtl"
      custom-class="demo-drawer"
      :close-on-press-escape="false"
      :wrapperClosable="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm form"
      >
        <el-form-item label="联系人名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入联系人名称"
          ></el-input>
          <!-- <el-input
            v-if="pageStart == 1"
            v-model="ruleForm.name"
            :disabled="true"
          ></el-input>
          <el-select
            v-else
            v-model="ruleForm.name"
            filterable
            remote
            allow-create
            default-first-option
            placeholder="请输入联系人名称"
            :remote-method="getExternal"
            :loading="contactsing"
            @change="companyChang($event)"
          >
            <el-option
              v-for="item in externalList"
              :key="item.external_userid"
              :label="item.name"
              :value="item.external_userid"
            >
            </el-option>
          </el-select> -->
        </el-form-item>
        <!-- <el-form-item label="联系人类型">
        <el-radio-group v-model="ruleForm.type">
          <el-radio :label="0">默认类型</el-radio>
        </el-radio-group>
      </el-form-item> -->
        <el-form-item label="标签">
          <el-select v-model="ruleForm.tag_id" filterable placeholder="请选择">
            <el-option
              v-for="item in labelList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="customer_id">
          <el-select v-model="ruleForm.customer_id" filterable placeholder="请选择">
            <el-option
              v-for="item in enterpriseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <i
            id="addComphone"
            class="el-icon-plus operable"
            style="color: #0276fe"
            @click="showCompone"
            >新增</i
          >
        </el-form-item>

        <el-form-item label="电话">
          <el-input
            v-show="false"
            v-model="formCon.imageBs"
            show-word-limit
            type="text"
          >
          </el-input>
          <div v-for="(item, index) in phoneSelList" :key="index">
            <el-form-item>
              <el-col :span="14"
                ><el-input
                  v-model="item.value"
                  @change="validateUrl($event, index)"
                  placeholder="请输入电话"
                  clearable
                  style="margin-bottom: 22px"
              /></el-col>
              <el-col :span="1">&nbsp;</el-col>
              <el-col :span="9"
                ><i
                  id="removePhone"
                  class="operable"
                  :class="index == 0 ? 'el-icon-circle-plus' : 'el-icon-remove'"
                  :style="{ color: index == 0 ? '#02B38B' : '#ff6b6b' }"
                  @click="phoneAraay(index)"
                ></i
              ></el-col>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="职务" prop="position">
          <el-input
            v-model="ruleForm.position"
            placeholder="请输入职务"
          ></el-input>
        </el-form-item>

        <el-form-item label="来源" prop="source">
          <el-select v-model="ruleForm.source" filterable placeholder="请选择">
            <el-option
              v-for="item in sourceList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省市县" required="required">
          <div style="margin-bottom: 22px">
            <!-- 省 -->
            <el-select
              v-model="ruleForm.pid"
              filterable
              placeholder="请选择省"
              @change="getProvince(1, ruleForm.pid, 1)"
            >
              <el-option
                v-for="item in provinceList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <!-- 市 -->
            <el-select
              v-if="cityList.length !== 0"
              filterable
              v-model="ruleForm.fid"
              placeholder="请选择市"
              @change="getProvince(2, ruleForm.fid, 1)"
            >
              <el-option
                v-for="item in cityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <!-- 区 -->
            <el-select
              v-if="areaList.length !== 0"
              filterable
              v-model="ruleForm.area_id"
              placeholder="请选择区"
              @change="areaChange($event)"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="ruleForm.address"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-col :span="11">
            <el-form-item>
              <el-date-picker
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                v-model="ruleForm.birthday"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="email">
          <el-input
            v-model="ruleForm.email"
            placeholder="请输入email"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证">
          <el-input
            v-model="ruleForm.id_card"
            placeholder="请输入身份证"
          ></el-input>
        </el-form-item>
        <el-form-item label="微信号">
          <el-input v-model="ruleForm.wx" placeholder="请输入微信号"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="ruleForm.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="foot_btn">
        <el-button @click="resetForm('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </div>
      <add-enterprise
        ref="enterpriseForm"
        :start="1"
        @getenterprise="getData"
      ></add-enterprise>
    </el-drawer>
  </div>
</template>

<script>
import addEnterprise from "./addEnterprise.vue";
export default {
  props: ["start", "detailsData"],
  components: {
    addEnterprise,
  },
  data() {
    return {
      pageStart: 0, // 当前页面新增|编辑标识
      drawer: false,
      title: "",
      enterpriseList: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      labelList: [],
      sourceList: [],
      externalList: [],
      // 外部联系人加载
      contactsing: false,
      // 省市选择
      address: {
        province: "",
        city: "",
        area: "",
        details: "",
      },
      // 电话列表
      formCon: { imageBs: "" },
      phoneSelList: [{ value: "" }],
      ruleForm: {
        external_userid: "",
        id: "",
        name: "",
        phone: "",
        tag_id: "",
        customer_id: "",
        position: "",
        source: "",
        pid: "",
        fid: "",
        area_id: "",
        address: "",
        birthday: "",
        email: "",
        sex: 1,
        id_card: "",
        wx: "",
        remark: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入联系人名称", trigger: "blur" },
        ],
        enterprise: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ],
        position: [{ required: true, message: "请输入职务", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        imageBs: [
          { required: true, message: "请至少输入一个电话", trigger: "change" },
        ],
        customer_id: [
          { required: true, message: "请选择企业", trigger: "change" },
        ],
        source: [{ required: true, message: "请选择企业", trigger: "change" }],
        external_userid: [
          { required: true, message: "请选择外部联系人", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    drawer(newData, oldData) {
      if (newData) {
        this.getData();
        this.getlabel();
        this.getsource();
        // this.getExternal();
        if (this.detailsData && this.detailsData.id) {
          this.pageStart = 1;
          this.title = "编辑联系人";
          this.ruleForm = this.detailsData;
          if (this.ruleForm.phone !== "") {
            let phone_ar = this.ruleForm.phone.split(",");
            this.phoneSelList = [];
            for (let i = 0; i < phone_ar.length; i++) {
              let param_ph = { value: phone_ar[i] };
              this.phoneSelList.push(param_ph);
            }
          }
          this.getProvince(0, "", 0);
          this.getProvince(1, this.ruleForm.pid, 0);
          this.getProvince(2, this.ruleForm.fid, 0);
        } else {
          this.pageStart = 0;
          this.title = "新增联系人";
          this.ruleForm = this.$options.data().ruleForm;
          this.phoneSelList = this.$options.data().phoneSelList;
          this.getProvince(0, "", 0);
        }
      }
    },
  },
  created() {},
  methods: {
    // 获取外部联系人
    getExternal(query) {
      if (query && query !== "") {
        this.contactsing = true;
        this.$cmsapi.searchExternalList(query).then(
          (res) => {
            if (res.code == 0) {
              this.externalList = res.data;
            } else {
              this.$message.error(res.msg);
            }
            this.contactsing = false;
          },
          (err) => {
            console.log(err);
          }
        );
      } else {
        this.externalList = this.$options.data().externalList;
      }
    },
    // 监听联系人名称是否为创建条目
    companyChang(obj) {
      if (this.externalList.length > 0) {
        this.ruleForm.external_userid = obj;
      } else {
        this.ruleForm.external_userid = 0;
      }
      console.log(obj, this.externalList);
    },
    // 获取企业
    getData() {
      this.$cmsapi.customerList().then(
        (res) => {
          if (res.code == 0) {
            for (let i = 0; i < res.data.length; i++) {
              for (const key in res.data[i]) {
                if (!res.data[i][key] && res.data[i][key] !== 0) {
                  res.data[i][key] = "";
                }
              }
            }
            this.enterpriseList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 获取标签下拉数据
    getlabel() {
      this.$cmsapi.labelLibraryList("ety3bHEAAAqPdHxJC2YR9f8BW4qPDQIQ").then(
        (res) => {
          if (res.code == 0) {
            this.labelList = res.data[0].tag;
          } else {
            this.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 获取来源下拉数据
    getsource() {
      this.$cmsapi.sourcelList().then(
        (res) => {
          if (res.code == 0) {
            this.sourceList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 省市区数据
    // type:级别
    // condition:参数
    // nothingness:是否为二次修改0否1是
    getProvince(type, condition, nothingness) {
      let that = this;
      this.$cmsapi.addressList(condition).then(
        (res) => {
          if (res.code == 0) {
            switch (type) {
              case 0:
                that.provinceList = res.data;
                if (that.ruleForm.pid == "") {
                  that.ruleForm.pid = res.data[0].id;
                  if (that.title == "新增联系人") {
                    that.getProvince(1, res.data[0].id, 0);
                  }
                }
                if (nothingness == 1) {
                  that.getProvince(1, that.ruleForm.pid, 1);
                }
                break;
              case 1:
                that.cityList = res.data;
                if (that.ruleForm.fid == "" || nothingness == 1) {
                  that.ruleForm.fid = res.data[0].id;
                  if (that.title == "新增联系人") {
                    that.getProvince(2, res.data[0].id, 0);
                  }
                }
                if (nothingness == 1) {
                  that.getProvince(2, that.ruleForm.fid, 1);
                }
                break;
              case 2:
                that.areaList = res.data;
                if (that.ruleForm.area_id == "" || nothingness == 1) {
                  that.ruleForm.area_id = res.data[0] ? res.data[0].id : "";
                }
                if (nothingness == 1) {
                  that.ruleForm.address = that.$options.data().ruleForm.address;
                }
                break;
              default:
                break;
            }
          } else {
            that.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 手机号监听
    validateUrl(ct, index) {
      let phoneValid = false;
      for (let i = 0; i < this.phoneSelList.length; i++) {
        if (this.phoneSelList[i].value && this.phoneSelList[i].value !== "") {
          phoneValid = true;
          break;
        }
      }
      if (phoneValid) {
        this.$set(this.formCon, "imageBs", "1");
      } else {
        this.$set(this.formCon, "imageBs", "");
      }
    },
    // 手机号数组操作
    phoneAraay(index) {
      if (index == 0) {
        // 数组扩展
        let param = {
          vlaue: "",
        };
        this.phoneSelList.push(param);
      } else {
        // 指定序号去除
        this.phoneSelList.splice(index, 1);
      }
    },
    // 新增企业
    showCompone() {
      this.$refs.enterpriseForm.dialogEditer = true;
    },
    // 取消&返回上一页
    resetForm() {
      this.drawer = false;
    },
    // 提交
    submitForm(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          for (let i = 0; i < that.phoneSelList.length; i++) {
            if (i == 0) {
              that.ruleForm.phone = that.phoneSelList[i].value;
            } else {
              that.ruleForm.phone =
                that.ruleForm.phone + "," + that.phoneSelList[i].value;
            }
          }
          for (let j = 0; j < that.externalList.length; j++) {
            if (that.externalList[j].external_userid == that.ruleForm.external_userid) {
              that.ruleForm.name = that.externalList[j].name;
              break;
            }
          }
          that.$cmsapi.contactsSave(that.ruleForm).then(
            (res) => {
              if (res.code == 0) {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                that.ruleForm = that.$options.data().ruleForm;
                this.drawer = false;
                if (this.start == "0") {
                  // 如果是最后抽屉跳转对应模块刷新数据
                  this.$router.push({
                    path: "/customer/contactsList",
                    query: {
                      t: Date.now(),
                    },
                  });
                } else {
                  // 刷新上一层抽屉相关数据
                  this.$emit("getobject");
                }
              } else {
                that.$message.error(res.msg);
              }
            },
            (err) => {
              that.$message.error(err);
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.body_all {
  height: auto;
  overflow-y: hidden;
  padding: 10px 20px 30px 30px;
  background-color: #fff;
}
.block_view {
  cursor: pointer;
}
.block_view:hover {
  color: #0276fe;
}
.renturn-icon {
  font-size: 24px;
  margin-right: 8px;
}
.form {
  width: 95%;
}
.addressTips {
  color: #a4adc0;
}
.addressTips span {
  cursor: pointer;
  margin-left: 5px;
  color: #1066ec;
}
</style>